import {designComponent, iHTMLDivElement, PropType, watch} from "@peryl/react-compose";
import {$useCmsRunningOption, $useRunningOption, eRenderDirection, PlainCmsNamespace, provideCmsRunningOption, RenderList,} from '@peryl/react-cms-editor';
import {DefaultRunningConfig} from "../../../modules/cms-visual-editor";
import {env} from "../../../env";
import {createEffects} from "@peryl/utils/createEffects";

export const ReactCmsRender = designComponent({
  name: 'react-cms-renderer',
  inheritPropsType: iHTMLDivElement,
  props: {
    dataMetas: { type: Array as PropType<PlainCmsNamespace.iDataMeta[]> }
  },
  setup({ props }) {

    const runningOption = $useRunningOption({ ...DefaultRunningConfig, isRunning: true });

    const cmsRunningOption = $useCmsRunningOption({
      runningOption: runningOption,
      effects: createEffects().effects,
      config: {
        isRunning: true,
        assetsPrefix: env.assetsPrefix,
        runningOptionConfig: DefaultRunningConfig,
        getSnapshot: {} as any,
        editorOptionConfig: {} as any,
      },
    });
    !!props.dataMetas && cmsRunningOption.state.updateStateData(props.dataMetas);

    provideCmsRunningOption(cmsRunningOption);

    watch(() => props.dataMetas, val => {cmsRunningOption.state.updateStateData(val ?? []);});

    return {
      refer: {
        runningOption,
        cmsRunningOption,
      },
      render: () => (
        <RenderList direction={eRenderDirection.vertical}/>
      )
    };
  },
});
